/**
 * tcp 服务端
 *  有客户端接入时，输出连接的客户端ip和客户端端口
 *  并写入当前系统时间
*/

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <time.h>

#include <arpa/inet.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

#define SERVER_PORT 8888

void signal_handler(int signum)
{
    if (signum == SIGINT)
    {
        printf("Server Quit\n");
        exit(EXIT_SUCCESS);
    }
}

void out_client_info(struct sockaddr_in clientAddr)
{
    char *ip = inet_ntoa(clientAddr.sin_addr);
    unsigned short port = ntohs(clientAddr.sin_port);
    printf("Connection from %s:%d\n", ip, port);
}

void out_time_to_client(int client_fd)
{
    time_t t = time(NULL);
    char *t_str = ctime(&t);
    write(client_fd, t_str, strlen(t_str));

    close(client_fd);
}

int main(void)
{

    struct sockaddr_in serverAddr, clientAddr;

    signal(SIGINT, signal_handler);

    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (0 > fd)
    {
        perror("socket error: ");
        exit(EXIT_FAILURE);
    }

    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(SERVER_PORT);
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(fd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr_in)) < 0)
    {
        perror("bind error: ");
        goto SOCK_ERROR;
    }

    if (listen(fd, 1) < 0)
    {
        perror("listen error: ");
        goto SOCK_ERROR;
    }

    socklen_t addrlen = sizeof(clientAddr);
    while (1)
    {
        int newfd = accept(fd, (struct sockaddr *)&clientAddr, &addrlen);
        if (newfd < 0)
        {
            perror("accept error: ");
            goto SOCK_ERROR;
        }

        out_client_info(clientAddr);
        out_time_to_client(newfd);
    }
    return 0;

SOCK_ERROR:
    close(fd);
    exit(EXIT_FAILURE);
}